package com.xingji.caixia.fragment;

import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.util.CircularArray;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.xingji.caixia.Constant;
import com.xingji.caixia.MyApplication;
import com.xingji.caixia.R;
import com.xingji.caixia.activity.MainActivity;
import com.xingji.caixia.adapter.PageAdapter;
import com.xingji.caixia.camera.CameraInterface;
import com.xingji.caixia.entitys.CardDao;
import com.xingji.caixia.entitys.CardData;
import com.xingji.caixia.entitys.InfoMessage;
import com.xingji.caixia.entitys.LunboData;
import com.xingji.caixia.entitys.MessageData;
import com.xingji.caixia.entitys.UploadData;


import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.ex.DbException;
import org.xutils.http.RequestParams;
import org.xutils.image.ImageOptions;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.xingji.caixia.View.AutoScrollViewPager;

@ContentView(R.layout.fragment_main)
public class MainFragment extends BaseFragment implements CameraInterface.CamOpenOverCallback,CameraInterface.BitmapCallback {

    @ViewInject(R.id.course_name)
    private TextView courseName;

    @ViewInject(R.id.course_cardnum)
    private TextView courseCardnum;

    @ViewInject(R.id.course_type)
    private TextView courseType;

    @ViewInject(R.id.course_residue)
    private TextView courseResidue;

    @ViewInject(R.id.surfaceview)
    SurfaceView surfaceview;

    @ViewInject(R.id.address)
    TextView address;

    @ViewInject(R.id.phone)
    TextView phone;

    @ViewInject(R.id.qrcode)
    ImageView qrcode;

    @ViewInject(R.id.edittext)
    private EditText edittext;

    @ViewInject(R.id.ad_pager)
    AutoScrollViewPager ad_pager;

    SurfaceHolder surfaceHolder;

    CircularArray<ImageView> imagelist;
    private PageAdapter pageAdapter;
    private ImageOptions imageOptions;
    private List<MessageData.ListBean> messageDatas = new ArrayList<>();
    private List<LunboData.ListBean> lunboList = new ArrayList<>();
    private List<String> imageUrls = new ArrayList<>();
    private InfoMessage.ListBean infoMessage = new InfoMessage().getList();

    CardData cardData;//// TODO: 2017/9/19 这是什么？卡信息实体？
    String CardNo;//卡号

    private static final String SCHOOL_ID = "school_id";
    private String school_id;

    private OnFragmentInteractionListener mListener;

    public static MainFragment newInstance(String school_id) {
        MainFragment fragment = new MainFragment();
        Bundle args = new Bundle();
        args.putString(SCHOOL_ID, school_id);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            school_id = getArguments().getString(SCHOOL_ID);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return x.view().inject(this,inflater,container);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initView();
    }

    private void initView(){

//        school_id = getActivity().getIntent().getStringExtra("school_id");
        imagelist = new CircularArray<>();
        pageAdapter = new PageAdapter();
        ad_pager.setAdapter(pageAdapter);
        ad_pager.setInterval(5000);
        ad_pager.setAutoScrollDurationFactor(3);
        ad_pager.startAutoScroll();
        //消息？
        RequestParams message = new RequestParams(Constant.MESSAGE);
        message.addQueryStringParameter("count", "3");
        message.addQueryStringParameter("school_id", school_id);
        Log.e("school_id",school_id);
        post(message,1);//1 的消息/公告处理 不要了

        //刷卡窗口监听
        edittext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }
            @Override
            public void afterTextChanged(Editable s) {
                if (s.toString().endsWith("\n")) {
                    Log.e("TAG", "afterTextChanged: s = " + s);
                    edittext.setText("");
                    getCardData(s.toString().trim().replace("\n", ""));
                }
            }
        });

//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                while (true){
//                    try {
//                        Thread.sleep(1000);
//                        mhandler.sendEmptyMessage(1);
//                    } catch (InterruptedException e) {
//                        e.printStackTrace();
//                    }
//
//                }
//            }
//        }).start();

        UpApp();
    }

    private void getCardData(String card_no) {
        this.CardNo = card_no;
        RequestParams requestParams = new RequestParams(Constant.CARD_DATA);
        requestParams.addBodyParameter("card_no", card_no);
        post(requestParams,4);
    }

    private void userData(CardData cardData) {
        if (cardData == null){
            courseName.setText(String.format("学生姓名:请连接网络!"));
            courseCardnum.setText(String.format("学生卡号:请连接网络!"));
            courseResidue.setText(String.format("今日扣课:请连接网络!"));
            courseType.setText(String.format("课程余量:请连接网络!"));
        }else{
            courseName.setText(String.format("学生姓名:%s", cardData.getStudent_name()));
            courseCardnum.setText(String.format("学生卡号:%s", cardData.getCard_no()));
            courseResidue.setText(String.format("今日扣课:%s节", "1"));
            courseType.setText(String.format("课程余量:%s节", cardData.getCount()));
        }
    }

    @Override
    public void postSuccess(JSONObject jsonObject, Integer tag) {
        super.postSuccess(jsonObject, tag);
        try {
            success(jsonObject,tag);
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void success(JSONObject jsonObject, Integer tag) throws JSONException {
        switch (tag){
            case 1://消息和基本资料
                if (jsonObject.getBoolean("status")){
                    messageDatas = JSON.parseArray(jsonObject.getString("list"), MessageData.ListBean.class);
                }
                RequestParams requestParams = new RequestParams(Constant.PIC);
                requestParams.addBodyParameter("count", "3");
                requestParams.addBodyParameter("school_id", school_id);
                post(requestParams,2);
                break;
            case 2://学校的图片轮播
                if (jsonObject.getBoolean("status")) {
                    lunboList = JSON.parseArray(jsonObject.getString("list"), LunboData.ListBean.class);
                    for (int i = 0; i < lunboList.size(); i++) {
                        ImageView imagelunbo = new ImageView(getActivity());
                        imagelunbo.setScaleType(ImageView.ScaleType.CENTER_CROP);
                        x.image().bind(imagelunbo, Constant.IMG_HOST + lunboList.get(i).getPic_url());
                        imagelist.addFirst(imagelunbo);
                    }
                    pageAdapter.notify(imagelist);
                }
                RequestParams infoRequestParams = new RequestParams(Constant.INFO);
                infoRequestParams.addBodyParameter("count", "3");
                infoRequestParams.addBodyParameter("school_id", school_id);
                post(infoRequestParams,3);
                break;
            case 3://学校信息资料
                infoMessage = JSON.parseObject(jsonObject.getString("list"), InfoMessage.ListBean.class);
                mListener.setSchoolName(infoMessage.getSchool_name());
                address.setText("地址: " + infoMessage.getAddress());
                phone.setText("联系方式："+ infoMessage.getMobile());
                break;
            case 4://刷卡数据 学生资料
                if (jsonObject.getBoolean("status")) {
                    toast(jsonObject.getString("content"));
                    Log.e("data",jsonObject.getString("list")+"");
                    cardData = JSON.parseObject(jsonObject.getString("list"), CardData.class);
                    Log.e("cardData",cardData.toString()+"");
                    userData(cardData);
                    CameraInterface.getInstance().doTakePicture();
                } else {
                    toast(jsonObject.getString("content"));
                }
                break;
            case 5://下载更新
                String url = jsonObject.getString("content");//  这里是返回的url 下面是下载App的位置
                if (TextUtils.isEmpty(url)) {
                    toast("当前已是最新版本");
                    return;
                }
                toast("发现新版本,开始后台下载安装");
                download(new RequestParams(url),6);
                break;
        }
    }

    @Override
    public void postError(Throwable ex, boolean isOnCallback, Integer tag) {
        super.postError(ex, isOnCallback, tag);
        switch (tag){
            case 4:
                userData(null);
                //没有网络也要加  准备拍照
                CameraInterface.getInstance().doTakePicture();
                break;
        }
    }

    //这里是当场结果  不应该处理上传？
    @Override
    public void result(String resultPath,String tmbPath) {
        Log.e("path",resultPath+"---"+tmbPath);
        UploadData data = new UploadData();
        data.setCard(this.CardNo);
        data.setImgPath(resultPath);
        data.setThumbImgPath(tmbPath);
        data.setTime(new Date());
        try {
            CardDao.addNewData(data);
            toast("打卡成功");
            ((MainActivity)getActivity()).myService.addUpload(data);
        } catch (DbException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void cameraHasOpened() {
        if (surfaceHolder == null) {
            mhandler.sendEmptyMessage(1);
            return;
        }
        CameraInterface.getInstance().doStartPreview(surfaceHolder, 1);
    }

    Handler mhandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case 1:
                    Log.e("gogo", "gogo");
                    ad_pager.setCurrentItem(ad_pager.getCurrentItem()+1);
                    break;
                case 5:
                    RequestParams requestParams = new RequestParams(Constant.APP_URL);
                    requestParams.addBodyParameter("version", MyApplication.getInstance().getVersionName());
                    MainFragment.this.post(requestParams,5);
                    break;
            }
        }
    };

    public void UpApp (){
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    mhandler.sendEmptyMessage(5);
                    try {
                        Thread.sleep(3600000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();

    }

    @Override
    public void onResume() {
        super.onResume();
        CameraInterface.getInstance().setBitmapCallback(this);
        surfaceHolder = surfaceview.getHolder();
        Handler mainHandler = new Handler(getActivity().getMainLooper());
        mainHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                CameraInterface.getInstance().doOpenCamera(MainFragment.this);
            }
        },1000);
    }


    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof OnFragmentInteractionListener) {
            mListener = (OnFragmentInteractionListener) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement OnFragmentInteractionListener");
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        CameraInterface.getInstance().doStopCamera();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
        void setSchoolName(String name);
    }

    private void toast(String msg){
        Toast.makeText(self,msg,Toast.LENGTH_SHORT).show();
    }
}
